package com.sita.tboard.roadtrust.detail;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.malinskiy.superrecyclerview.OnMoreListener;
import com.malinskiy.superrecyclerview.SuperRecyclerView;
import com.sita.bike.R;
import com.sita.bike.model.EaseUser2;
import com.sita.bike.persistence.RtResourceEntity;
import com.sita.bike.persistence.RtResourceEntityDao;
import com.sita.bike.persistence.TrendMember;
import com.sita.bike.support.GlobalContext;
import com.sita.bike.utils.PersistUtils;
import com.sita.friend.FriendHelper;
import com.sita.tboard.ActivityBase;
import com.sita.tboard.global.LocalConstants;
import com.sita.tboard.roadtrust.event.RtNoteRefreshEvent;
import com.sita.tboard.roadtrust.gridimage.RtResourceGalleryAdapter;
import com.sita.tboard.roadtrust.helper.RtGeneralHelper;
import com.sita.tboard.roadtrust.helper.RtNoteNetworkHelper;
import com.sita.tboard.ui.tools.AudioPlayer;
import com.sita.tboard.util.DateUtils;
import com.sita.tboard.view.MyDividerItemDecoration;
import com.sita.tboard.view.ImageModel;
import com.sita.tboard.view.NineGridlayout;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by xiaodong on 16/1/26.
 */
public class RtNoteListActivity extends ActivityBase implements LoaderManager.LoaderCallbacks<Cursor>,
        OnMoreListener {

    @Bind(R.id.avatar)
    CircleImageView avatarView;
    @Bind(R.id.nickname)
    TextView nicknameView;
    @Bind(R.id.item_voice)
    ImageView voiceView;
    @Bind(R.id.item_time)
    TextView timeView;
    @Bind(R.id.item_content)
    TextView viewContent;
    @Bind(R.id.item_gallery)
    NineGridlayout galleryView;

    @Bind(R.id.message)
    EditText messageView;

    @Bind(R.id.note_list)
    SuperRecyclerView noteListView;

    private RtNoteListAdapter listAdapter;

    private RtResourceGalleryAdapter galleryAdapter;

    private int currPage;

    @Bind(R.id.toolbar)
    Toolbar toolbar;

    private AudioPlayer player;
    private AnimationDrawable mAnimationDrawable;

    private String mResourceId;

    private Context mContext;

    public static Intent newIntent(String resourceId) {
        Intent intent = new Intent(GlobalContext.getGlobalContext(), RtNoteListActivity.class);
        intent.putExtra(LocalConstants.BIND_RESOURCE_ID, resourceId);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rt_resource_detail);
        ButterKnife.bind(this);

        mContext = this;

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationIcon(R.mipmap.ic_back);

        player = getPlayer();

        mResourceId = getIntent().getStringExtra(LocalConstants.BIND_RESOURCE_ID);
        if (TextUtils.isEmpty(mResourceId)) {
            finish();
            return;
        }

        loadRtResource();

        initNoteList();

        currPage = 0;
        RtNoteNetworkHelper.getInstance().getNoteList(mResourceId, currPage);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private AudioPlayer getPlayer() {
        if (player != null) {
            if (player.isPlaying())
                player.stop();
        } else {
            player = new AudioPlayer();
        }
        //if everything ok play file
        //in case of any error return from method before (catch)
        return player;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (player != null && player.isPlaying()) {
            player.pause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (player != null) {
            player.stop();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        return new RtNoteCursorLoader(GlobalContext.getGlobalContext());
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        listAdapter.swapCursor(data);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        listAdapter.swapCursor(null);
    }

    @Override
    public void onMoreAsked(int overallItemsCount, int itemsBeforeMore, int maxLastVisiblePosition) {
        currPage += 1;
        RtNoteNetworkHelper.getInstance().getNoteList(mResourceId, currPage);
    }


    public void onEventMainThread(RtNoteRefreshEvent event) {
        switch (event.getMode()) {
            case NEW_NOTE:
                messageView.setText(null);
            case MORE:
                noteListView.setLoadingMore(false);
            case REFRESH:
                getSupportLoaderManager().restartLoader(LocalConstants.RT_NOTE_LOADER, null, this);
        }
    }

    @OnClick(R.id.btn_send)
    void btnSendClick() {
        if (TextUtils.isEmpty(messageView.getText().toString())) {
            return;
        }
        String message = messageView.getText().toString();
        RtNoteNetworkHelper.getInstance().sendNote(mResourceId, message);
    }

    private void loadRtResource() {
        RtResourceEntityDao dao = GlobalContext.getDaoSession().getRtResourceEntityDao();
        RtResourceEntity entity = dao.load(Long.valueOf(mResourceId));
        viewContent.setText(entity.getTitle());

        String time = DateUtils.translateDateTime(entity.getCreateDate());
        timeView.setText(time);

        String accountId = entity.getAccountId();
        fillAccount(accountId);

        String pics = entity.getPics();
        String thumbnails = entity.getThumbnails();
        String orgpicname = entity.getOrgpicname();
        String audios = entity.getAudios();

        fillImage(pics, thumbnails, orgpicname);
    }

    private void fillAccount(String accountId) {
        String avatar = null;
        String nickname = null;
        EaseUser2 friend = FriendHelper.getInstance().getContactUser(accountId);
        if (friend != null) {
            avatar = friend.getAvatar();
            nickname = friend.getUsername().equals("") ? friend.getNick() : friend.getUsername();
        } else {
            // 非好友
            TrendMember member = PersistUtils.getTrendMember(accountId);
            if (member != null) {
                avatar = member.getAvatarUrl();
                nickname = member.getNickname();
            }
        }
        Picasso.with(GlobalContext.getGlobalContext()).load(avatar).fit()
                .placeholder(R.drawable.default_head)
                .centerInside().into(avatarView);
        nicknameView.setText(nickname);
    }

    private void fillImage(String pics, String thumbnails, String orgpicname) {
        if (!TextUtils.isEmpty(thumbnails)) {
            String[] thumbs = TextUtils.split(thumbnails, ",");
            List<ImageModel> imageModels = new ArrayList<ImageModel>();
            if (thumbs.length == 1) {
                int point = orgpicname.indexOf(".");
                String name = point > -1 ? orgpicname.substring(0, point) : orgpicname;
                if (name.matches("(\\d+)x(\\d+)")) {
                    int x = name.indexOf("x");
                    String width = name.substring(0, x);
                    String height = name.substring(x + 1);
                    imageModels.add(new ImageModel().setUrl(thumbs[0])
                            .setWidth(Integer.valueOf(width))
                            .setHeight(Integer.valueOf(height)));
                } else {
                    imageModels.add(new ImageModel().setUrl(thumbs[0]));
                }
            } else {
                for (int i = 0; i < thumbs.length; i++) {
                    imageModels.add(new ImageModel().setUrl(thumbs[i]));
                }
            }
            final ArrayList<String> bigPics = new ArrayList<String>();
            String[] picUrls = TextUtils.split(pics, ",");
            for (int i = 0; i < picUrls.length; i++) {
                bigPics.add(picUrls[i]);
                if (i == 0) {
                    //firstPic = picUrls[i];
                }
            }
            galleryAdapter = new RtResourceGalleryAdapter(mContext, imageModels);
            galleryView.setAdapter(galleryAdapter);

            galleryView.setOnItemClickListerner(new com.sita.tboard.view.NineGridlayout.OnItemClickListerner() {
                @Override
                public void onItemClick(View view, int position) {
                    RtGeneralHelper.showPicture(mContext, position, bigPics);
                }
            });

            galleryView.setVisibility(View.VISIBLE);
        } else {
            galleryView.setVisibility(View.GONE);
        }
    }

    private void initNoteList() {
        noteListView.setLayoutManager(new LinearLayoutManager(this,
                OrientationHelper.VERTICAL, true));

        Drawable drawable = new ColorDrawable(getResources().getColor(R.color.divider_list));
        noteListView.addItemDecoration(new MyDividerItemDecoration(drawable, true, true));

        noteListView.setupMoreListener(this, 1);

        noteListView.setRefreshListener(null);

        listAdapter = new RtNoteListAdapter(this);
        noteListView.setAdapter(listAdapter);
    }
}
